<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">




<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
  </script>






<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />



  <link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico?v=5.1.4">







  <meta name="keywords" content="iOS," />





  <link rel="alternate" href="/atom.xml" title="Swift社区" type="application/atom+xml" />






<meta name="description" content="在之前的文章中，我们看了一些使用依赖注入的不同方法，以实现Swift应用中更多的解耦和可测试架构。例如， “在Swift中使用工厂的依赖注入”中把依赖注入和工厂模式结合起来，以及“在Swift中避免使用单例” 中利用依赖注入取代单利。 到目前为止，我的大部分文章和例子都使用了基于初始化器的依赖注入。然而，就像大多数编程技术一样，依赖注入有多种“风味(Flavors)”，每一种都有自己的优点和缺点。">
<meta name="keywords" content="iOS">
<meta property="og:type" content="article">
<meta property="og:title" content="Swift 中风味各异的依赖注入">
<meta property="og:url" content="https://fanbaoying.github.io/Swift-中风味各异的依赖注入/index.html">
<meta property="og:site_name" content="Swift社区">
<meta property="og:description" content="在之前的文章中，我们看了一些使用依赖注入的不同方法，以实现Swift应用中更多的解耦和可测试架构。例如， “在Swift中使用工厂的依赖注入”中把依赖注入和工厂模式结合起来，以及“在Swift中避免使用单例” 中利用依赖注入取代单利。 到目前为止，我的大部分文章和例子都使用了基于初始化器的依赖注入。然而，就像大多数编程技术一样，依赖注入有多种“风味(Flavors)”，每一种都有自己的优点和缺点。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2022-03-31T02:07:11.672Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Swift 中风味各异的依赖注入">
<meta name="twitter:description" content="在之前的文章中，我们看了一些使用依赖注入的不同方法，以实现Swift应用中更多的解耦和可测试架构。例如， “在Swift中使用工厂的依赖注入”中把依赖注入和工厂模式结合起来，以及“在Swift中避免使用单例” 中利用依赖注入取代单利。 到目前为止，我的大部分文章和例子都使用了基于初始化器的依赖注入。然而，就像大多数编程技术一样，依赖注入有多种“风味(Flavors)”，每一种都有自己的优点和缺点。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://fanbaoying.github.io/Swift-中风味各异的依赖注入/"/>





  <title>Swift 中风味各异的依赖注入 | Swift社区</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    
    <a href="https://github.com/SwiftCommunityRes" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
    
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Swift社区</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">做最好的 Swift 社区</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://fanbaoying.github.io/Swift-中风味各异的依赖注入/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Swift社区">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://avatars.githubusercontent.com/u/84354365?v=4">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Swift社区">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Swift 中风味各异的依赖注入</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2022-03-31T10:03:09+08:00">
                2022-03-31
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Swift/" itemprop="url" rel="index">
                    <span itemprop="name">Swift</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                <!-- 
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                -->
                <span title="字数统计">
                  数字统计 1,967字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>

                <!-- 
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                --> 

                <span title="阅读时长">
                  阅读时长 7分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>在之前的文章中，我们看了一些使用依赖注入的不同方法，以实现Swift应用中更多的解耦和可测试架构。例如， <a href="https://www.swiftbysundell.com/articles/dependency-injection-using-factories-in-swift" target="_blank" rel="noopener">“在Swift中使用工厂的依赖注入”</a>中把依赖注入和工厂模式结合起来，以及<em><a href="https://www.swiftbysundell.com/articles/avoiding-singletons-in-swift" target="_blank" rel="noopener">“在Swift中避免使用单例”</a></em> 中利用依赖注入取代单利。</p>
<p>到目前为止，我的大部分文章和例子都使用了基于初始化器的依赖注入。然而，就像大多数编程技术一样，依赖注入有多种“风味(Flavors)”，每一种都有自己的优点和缺点。本周，让我们来看看三种不同方式的依赖注入，以及它们如何在Swift中使用。</p>
<a id="more"></a>
<h1 id="基于初始化器"><a href="#基于初始化器" class="headerlink" title="基于初始化器"></a>基于初始化器</h1><p>让我们先快速回顾一下最常见的依赖注入方式——基于初始化器的依赖注入，即对象在被初始化时应该被赋予它所需要的依赖关系。这种方式的最大好处是，它保证我们的对象拥有它们所需要的一切，以便立即开展工作。</p>
<p>假设我们正在构建一个从磁盘上加载文件的<code>FileLoader</code>。为了做到这一点，它使用了两个依赖项——一个是系统提供的<code>FileManager</code>的实例，另一个是<code>Cache</code>。使用基于初始化器的依赖注入，可以这样实现:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">FileLoader</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">let</span> fileManager: <span class="type">FileManager</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">let</span> cache: <span class="type">Cache</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">init</span>(fileManager: <span class="type">FileManager</span> = .<span class="keyword">default</span>,</span><br><span class="line">         cache: <span class="type">Cache</span> = .<span class="keyword">init</span>()) &#123;</span><br><span class="line">        <span class="keyword">self</span>.fileManager = fileManager</span><br><span class="line">        <span class="keyword">self</span>.cache = cache</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>注意上面是如何使用默认参数的，以避免在使用单例或新实例时总是创建依赖关系。这使我们能够在生产代码中使用<code>FileLoader()</code>简单地创建一个文件加载器，同时仍然能够通过在测试代码中注入模拟数据或显式实例进行测试。</p>
<h1 id="基于属性"><a href="#基于属性" class="headerlink" title="基于属性"></a>基于属性</h1><p>虽然基于初始化器的依赖注入通常很适合你自己的自定义类，但有时当你必须从系统类继承时，它就有点难用了。一个例子是在构建视图控制器时，特别是当你使用 XIBs 或 Storyboards 来定义它们时，因为这样你就无法再控制你的类的初始化器了。</p>
<p>对于这些类型的情况，基于属性的依赖注入可以是一个很好的选择。与其在对象的初始化器中注入对象的依赖关系，不如在之后简单地将其分配。这种依赖注入的方式也可以帮助你减少模板文件，特别是当有一个好的默认值不一定需要注入的时候。</p>
<p>让我们来看看另一个例子——在这个例子中，我们要建立一个<code>PhotoEditorViewController</code>，让用户编辑他们库中的一张照片。为了发挥作用，这个视图控制器需要一个系统提供的<code>PHPhotoLibrary</code>类的实例（它是一个单例），以及一个我们自己的<code>PhotoEditorEngine</code>类的实例。为了在没有自定义初始化器的情况下实现依赖性注入，我们可以创建两个都有默认值的可变属性，就像这样:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">PhotoEditorViewController</span>: <span class="title">UIViewController</span> </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> library: <span class="type">PhotoLibrary</span> = <span class="type">PHPhotoLibrary</span>.shared()</span><br><span class="line">    <span class="keyword">var</span> engine = <span class="type">PhotoEditorEngine</span>()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>请注意 <em><a href="https://www.swiftbysundell.com/articles/testing-swift-code-that-uses-system-singletons-in-3-easy-steps" target="_blank" rel="noopener">“通过 3 个简单的步骤测试使用了系统单例的 Swift 代码”</a></em>中的技术是如何通过使用协议来为系统照片库类提供一个更抽象的<code>PhotoLibrary</code>接口。这将使测试和数据模拟变得更加容易!</p>
<p>上述做法的好处是，我们仍然可以很容易地在测试中注入模拟数据，只需重新分配视图控制器的属性：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">PhotoEditorViewControllerTests</span>: <span class="title">XCTestCase</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">testApplyingBlackAndWhiteFilter</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">let</span> viewController = <span class="type">PhotoEditorViewController</span>()</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 分配一个模拟照片库以完全控制里面存储了哪些照片</span></span><br><span class="line">        <span class="keyword">let</span> library = <span class="type">PhotoLibraryMock</span>()</span><br><span class="line">        library.photos = [<span class="type">TestPhotoFactory</span>.photoWithColor(.red)]</span><br><span class="line">        viewController.library = library</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 运行我们的测试命令</span></span><br><span class="line">        viewController.selectPhoto(atIndex: <span class="number">0</span>)</span><br><span class="line">        viewController.apply(<span class="built_in">filter</span>: .blackAndWhite)</span><br><span class="line">        viewController.savePhoto()</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 断言结果是正确的</span></span><br><span class="line">        <span class="type">XCTAssertTrue</span>(photoIsBlackAndWhite(library.photos[<span class="number">0</span>]))</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="基于参数"><a href="#基于参数" class="headerlink" title="基于参数"></a>基于参数</h1><p>最后，让我们看一下基于参数的依赖注入。当你想轻松地使遗留代码变得更容易测试且不必过多地改变其现有结构时，这种类型特别有用。</p>
<p>很多时候，我们只需要一个特定的依赖关系一次，或者我们只需要在某些条件下模拟它。我们不需要改变对象的初始化器或将属性暴露为可变的（这并不总是一个好方式），而是可以开放某个API来接受一个依赖关系作为参数。</p>
<p>让我们来看看一个<code>NoteManager</code>类，它是一个记事应用程序的一部分。它的工作是管理用户所写的所有笔记，并提供一个API用于根据查询来搜索笔记。由于这是一个可能需要一段时间的操作（如果用户有很多笔记的话，这是很有可能的），我们通常在一个后台队列中执行，像这样:</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">NoteManager</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">loadNotes</span><span class="params">(matching query: String,</span></span></span><br><span class="line"><span class="function"><span class="params">                   completionHandler: @escaping <span class="params">([Note])</span></span></span> -&gt; <span class="type">Void</span>) &#123;</span><br><span class="line">        <span class="type">DispatchQueue</span>.global(qos: .userInitiated).async &#123;</span><br><span class="line">            <span class="keyword">let</span> database = <span class="keyword">self</span>.loadDatabase()</span><br><span class="line">            <span class="keyword">let</span> notes = database.<span class="built_in">filter</span> &#123; note <span class="keyword">in</span></span><br><span class="line">                <span class="keyword">return</span> note.matches(query: query)</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            completionHandler(notes)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>虽然上述方法对我们的生产代码来说是一个很好的解决方案，但在测试中，我们通常希望尽可能地避免异步代码和并行性，以<a href="https://www.swiftbysundell.com/articles/reducing-flakiness-in-swift-tests" target="_blank" rel="noopener">避免片状现象</a>。虽然使用初始化器或基于属性的依赖注入来指定<code>NoteManager</code>应始终使用的显式队列会很好，但这可能需要对类进行大的修改，而我们现在还不能/不愿意这样做。</p>
<p>这就是基于参数的依赖性注入的作用。与其重构我们的整个类，不如直接注入要在哪个队列上运行<code>loadNotes</code>操作：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">NoteManager</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">loadNotes</span><span class="params">(matching query: String,</span></span></span><br><span class="line"><span class="function"><span class="params">                   on queue: DispatchQueue = .global<span class="params">(qos: .userInitiated)</span></span></span>,</span><br><span class="line">                   completionHandler: @escaping ([<span class="type">Note</span>]) -&gt; <span class="type">Void</span>) &#123;</span><br><span class="line">        queue.async &#123;</span><br><span class="line">            <span class="keyword">let</span> database = <span class="keyword">self</span>.loadDatabase()</span><br><span class="line">            <span class="keyword">let</span> notes = database.<span class="built_in">filter</span> &#123; note <span class="keyword">in</span></span><br><span class="line">                <span class="keyword">return</span> note.matches(query: query)</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            completionHandler(notes)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这使我们能够在测试代码中轻松地使用一个自定义队列，我们可以在上面等待。这几乎可以让我们在测试中把上述API变成一个同步的API，这让事情变得更容易和更可预测。</p>
<p>基于参数的依赖注入的另一个用例是当你想测试静态API的时候。对于静态API，我们没有初始化器，而且我们最好也不要静态地保持任何状态，所以基于参数的依赖注入成为一个很好的选择。让我们看一个当前依赖单例的静态<code>MessageSender</code> 类：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MessageSender</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="keyword">func</span> <span class="title">send</span><span class="params">(<span class="number">_</span> message: Message, to user: User)</span></span> <span class="keyword">throws</span> &#123;</span><br><span class="line">        <span class="type">Database</span>.shared.insert(message)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">let</span> data: <span class="type">Data</span> = <span class="keyword">try</span> wrap(message)</span><br><span class="line">        <span class="keyword">let</span> endpoint = <span class="type">Endpoint</span>.sendMessage(to: user)</span><br><span class="line">        <span class="type">NetworkManager</span>.shared.post(data, to: endpoint.url)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>虽然理想的长期解决方案可能是重构<code>MessageSender</code>，使其成为非静态的，并在其使用的任何地方正确注入，但为了方便测试（例如，为了重现/验证一个错误），我们可以简单地将其依赖性作为参数注入，而不是依赖单例：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MessageSender</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="keyword">func</span> <span class="title">send</span><span class="params">(<span class="number">_</span> message: Message,</span></span></span><br><span class="line"><span class="function"><span class="params">                     to user: User,</span></span></span><br><span class="line"><span class="function"><span class="params">                     database: Database = .shared,</span></span></span><br><span class="line"><span class="function"><span class="params">                     networkManager: NetworkManager = .shared)</span></span> <span class="keyword">throws</span> &#123;</span><br><span class="line">        database.insert(message)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">let</span> data: <span class="type">Data</span> = <span class="keyword">try</span> wrap(message)</span><br><span class="line">        <span class="keyword">let</span> endpoint = <span class="type">Endpoint</span>.sendMessage(to: user)</span><br><span class="line">        networkManager.post(data, to: endpoint.url)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们再次使用默认参数，除去为了方便的原因，但这里更重要的是为了能够在我们的代码中添加测试支持，同时仍然保持100%的向后兼容性👍。</p>
<p>感谢您的阅读 🚀</p>

      
    </div>
    
    
    
    

    
      <div>
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      </div>
    


    
      <div>
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/Swift-中风味各异的依赖注入/">Swift 中风味各异的依赖注入</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 Swift社区 的个人博客">Swift社区</a></p>
  <p><span>发布时间:</span>2022年03月31日 - 10:03</p>
  <p><span>最后更新:</span>2022年03月31日 - 10:03</p>
  <p><span>原始链接:</span><a href="/Swift-中风味各异的依赖注入/" title="Swift 中风味各异的依赖注入">https://fanbaoying.github.io/Swift-中风味各异的依赖注入/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://fanbaoying.github.io/Swift-中风味各异的依赖注入/"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>

      </div>
    


    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="Swift社区 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="Swift社区 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/iOS/" rel="tag"><i class="fa fa-tag"></i> iOS</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/LeetCode-23-合并-K-个升序链表（Top-100）/" rel="next" title="LeetCode - 23 合并 K 个升序链表（Top 100）">
                <i class="fa fa-chevron-left"></i> LeetCode - 23 合并 K 个升序链表（Top 100）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/Swift-中风味各异的类型擦除/" rel="prev" title="Swift 中风味各异的类型擦除">
                Swift 中风味各异的类型擦除 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://avatars.githubusercontent.com/u/84354365?v=4"
                alt="Swift社区" />
            
              <p class="site-author-name" itemprop="name">Swift社区</p>
              <p class="site-description motion-element" itemprop="description">我们的使命是做一个最专业最权威的 Swift 中文社区，我们的愿景是希望更多的人学习和使用Swift。我们会分享以 Swift 实战、SwiftUI、Swift 基础为核心的技术干货，不忘初心，牢记使命。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">187</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_36478920" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://juejin.im/user/5a30d987f265da430d580126" target="_blank" title="掘金">
                      
                        <i class="fa fa-fw fa-spinner"></i>掘金</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/fanbaoying" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/swift-community" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/u/7711465033" target="_blank" title="微博">
                      
                        <i class="fa fa-fw fa-weibo"></i>微博</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzAxNzgzNTgwMw==&action=getalbum&album_id=2024314764775981057" target="_blank" title="公众号">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>公众号</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/SwiftCommunityRes/SwiftWeekly" title="SwiftWeekly" target="_blank">SwiftWeekly</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/SwiftCommunityRes/article-ios" title="Article-ios" target="_blank">Article-ios</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/SwiftCommunityRes/SwiftUI-Book" title="SwiftUI-Book" target="_blank">SwiftUI-Book</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#基于初始化器"><span class="nav-number">1.</span> <span class="nav-text">基于初始化器</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#基于属性"><span class="nav-number">2.</span> <span class="nav-text">基于属性</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#基于参数"><span class="nav-number">3.</span> <span class="nav-text">基于参数</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Swift社区</span>

  
</div>

<!-- 
<div class="powered-by">
  <i class="fa fa-user-md">
  </i>
  <span id="busuanzi_container_site_uv">
    已有<span id="busuanzi_value_site_uv"></span>人来访
  </span>

</div>


  <span class="post-meta-divider">|</span>


<div class="powered-by">
  <i class="fa fa-eye"></i>
  <span id="busuanzi_container_site_pv">
      访问量<span id="busuanzi_value_site_pv"></span>次
  </span>
</div>



  <span class="post-meta-divider">|</span>


-->

<div class="theme-info">
  <i class="fa fa-pencil"></i>
  <span class="post-count">博客全站共361.6k字</span>
</div>


<!-- 
  <span class="post-meta-divider">|</span>



  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>



-->

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
